<?php
/**
 * Created by PhpStorm.
 * User: TianFeng
 * Date: 2018/1/2
 * Time: 10:42
 */
namespace app\merchant\service;
use app\common\lib\Api;
use app\common\lib\Sftp;
use app\common\lib\Component;
use app\merchant\model\TpAccount;
use app\merchant\model\User;
use app\merchant\model\UserCompany;
use app\merchant\model\UserMoneyLog;
use Illuminate\Contracts\Logging\Log;
use think\Exception;
use app\merchant\model\TpMerchant;
use Vinelab\Http\Client;
use think\Session;
use app\merchant\model\BankCard;
use app\merchant\model\MerchantConfig;

class UserService{

    //实名认证 返回实名结果
    public static function userRealeNameObj($int_id, $str_realeName,$str_idcard){
        $params = [
            'user_id'=>$int_id,
            'real_name'=>$str_realeName,
            'id_card'=>$str_idcard,
        ];
        $ret = Api::doRequest(Api::PERSONAL_REAL,Api::GET,$params);

        return $ret;
    }

    //实名认证接口接口
   public static function userRealName($int_id, $str_realeName,$str_idcard){
       $params = [
           'user_id'=>$int_id,
           'real_name'=>$str_realeName,
           'id_card'=>$str_idcard,
       ];
       $res =  Api::doRequest(Api::PERSONAL_REAL, Api::GET, $params);

       if($res['code'] == 0){
           User::where('uid',$int_id)->update([ 'real_name'=>$str_realeName,'idcard'=>$str_idcard]);
           return true;
       }
       else{
           return false;
       }


   }

    // 借款人注册
    public static function borrowUserReg($int_phone, $int_merchant_id,
                                         $str_passwd = '123456',
                                         $int_userType = User::USER_TYPE_PERSON){
        $params =[
            'phone'=>$int_phone,
            'password'=>md5($str_passwd),
            'merchant_id'=>$int_merchant_id,
            'user_type'=>$int_userType,
        ];
        $ret = Api::doRequest(Api::ADD_BORROWER,Api::GET,$params);

        return $ret;
    }

    //商户注册
    public static function addMerchantApi($int_phone,$str_email,$int_userType, $int_role, $str_passwd = '123456'){
        $params =[
            'phone'=>$int_phone,
            'password'=>$str_passwd,
            'role'=>$int_role,
            'user_type'=>$int_userType,
            'email'=>$str_email,
        ];
        $ret = Api::doRequest(Api::MERCHANT_REGISTER,Api::GET,$params);

        return $ret;
    }


    //设置支付密码接口
    public static function setSinaPayPasswd($int_uid, $str_platform='PC', $return_url=''){
        $params = [
            'user_id'=>$int_uid,
            'platform'=>$str_platform,
            'return_url'=>$return_url,
        ];
        $ret = Api::doRequest(Api::SET_PAY_PASSWORD,Api::GET,$params);

        return $ret;
    }


    /**
     * 单个账户银行卡列表
     * @param array $condition
     * @return array $arr_card
     */
    public static function getUserBankList($condition)
    {
        $arr_card = db('bank_card')->where($condition)->select()->toArray();
        return $arr_card;
    }

    /**
     * 获取用户的资金明细
     * @param int $user_id
     * @param array $condition
     * @param int $page
     * @param int $limit
     * @return
     */
    public static function get_user_moneylog($user_id,$condition = [],$page=1,$limit=15)
    {
        $model = UserMoneyLog::where('user_id','=',$user_id);

        if (!empty($condition['start_time'])) {
            $model->where('add_time','>=',$condition['start_time']);
        }
        if (!empty($condition['end_time'])) {
            $model->where('add_time','<=',$condition['end_time']);
        }

        $return['count'] = $model->count();

        $return['list'] = $model->paginate($page,$limit);

        return $return;
    }

    /**
     * 商户账户可用余额
     * @param int $user_id
     * @return float
     */
    public static function get_account_balance($user_id)
    {
        $account =  TpAccount::where('user_id','=',$user_id)->find();
        if($account){
            return $account->balance;
        }
        return 0;
    }

    public static function get_user($user_id =0){

        if(!$user_id){
            return Session('user_info');
        }

        $user =  User::where('uid','=',$user_id)->find();
        if($user){
            return $user->toArray();
        }
        return [];
    }

    public static function getRePayMoney($uid,$day){

    }

    /**
     * 设置用户登录信息
     * @param $uid
     */
    public static function set_user($uid){
        if($uid){
            $user = User::where('uid',$uid)->field(['uid','user_type','role','real_name',
                'is_set_pay_password','is_set_handle_withhold_authority','user_email'])->find()->toArray();
            if($user['user_type'] == 1){
                $user_bank = BankCard::where('user_id',$user['uid'])->field('id')->find();
                $user['user_bank']= 0;
                if($user_bank)
                {
                    $user['user_bank']= 1;
                }
            }
            else{
                $user_company = UserCompany::where('user_id',$user['uid'])
                    ->field(['status','company_name'])
                    ->find();

                if($user_company){
                    $user_company = $user_company->toArray();
                    $user['user_company'] = $user_company;
                }

            }

            //商户资质
            $merchant = TpMerchant::where('user_id',$user['uid'])->find();
            if(empty($merchant) || $merchant->status !=1) {
                $user['merchant'] = 0;
                $user['merchant_show_type'] = [];
            }
            else{
                $user['merchant'] = 1;
                //商户展业类型（允许导入的类型1-车贷,2-消费贷,3-企业贷）
                $user['merchant_show_type'] = explode(',',$merchant->show_type);
            }

            //读取账户数据
            $tp_account = TpAccount::where('user_id',$user['uid'])->find();

            if($tp_account){
                $tp_account = $tp_account->toArray();
            }

            $user['account'] = $tp_account;

            $user['expire'] = time() + 12000;

            Session::set('user_info',$user);


            return $user;
        }
        return false;
    }

    //添加商户信息 将商户开户资料放置一个文件夹  一边上传进行开户

    // 用户登陆
    public static function login($name,$password)
    {
        $login['phone'] = $name;
        $login['password'] = md5($password);

        return Api::doRequest(Api::LOGIN_URL,Api::GET,$login);
    }

    /**
     * 根据手机注册开户
     * @param $phone
     * @param $password
     * @param int $type
     * @param string $email
     * @return bool|mixed
     */
    public static function regByPhone($phone,$password,$type = 1,$email = ''){
        if($type == User::USER_TYPE_PERSON){
            if(static::checkUserPhone($phone)){
                throw new Exception('此手机号已存在');
            }
        }
        else{
            if($email == ''){
                throw new Exception('企业开户邮箱不能为空');
            }
            if(static::checkUserPhoneOrEmail($phone,$email)){
                throw new Exception('该手机号码或邮箱已存在');
            }
        }

        $register['phone'] = $phone;
        $register['password'] = md5($password);
        $register['user_type'] = $type;
        $register['platform'] = 5;
        $register['email'] = $email;
        $register['role'] = 3;

        //注册开户
        $user = Api::doRequest(Api::MERCHANT_REGISTER,Api::GET,$register);

        return $user;
    }

    public static function addMerchant($user_id){
        $merchant['user_id']=  $user_id;
        $merchant['created_at']=time();
        TpMerchant::create($merchant);
    }

    /**
     * 检查手机号码是否已注册
     * @param $phone
     * @return bool
     */
    public static function checkUserPhone($phone){
        $oUser =  User::where('user_phone' , '=' ,$phone)->find();
        if($oUser) {
            return true;
        }
        return false;
    }

    /**
     * 检查手机和邮箱是否已存在
     * @param $phone
     * @param $email
     * @return bool
     */
    public static function checkUserPhoneOrEmail($phone,$email)
    {
        $oUser =  User::where('user_phone' , '=' ,$phone)->whereOr('user_email','=',$email)->find();
        if($oUser) {
            return true;
        }
        return false;
    }



    /**
     * 个人商户 实名认证
     * @param user_id  int 用户uid
     * @param id_card int  身份证
     * @param real_name  string 姓名
     * @return bool
     */
    public static function verity($user_id,$id_card,$real_name)
    {
        $user['user_id'] =  $user_id;
        $user['id_card'] =  $id_card;
        $user['real_name'] =  $real_name;
        //调用底层 进行实名认证
        $result =  Api::doRequest(Api::PERSONAL_REAL,Api::GET,$user);
        if($result['code']==0) {
            return $result['real_name'];
        }
        return false;
    }
    /**
     * 绑定银行卡
     * @param bank_code  string  银行卡
     * @param phone   int   手机号
     * @param province string   省
     * @param city  string   市
     * @param bank_card string 银行卡
     * @param user_id  int   用户id
     * @return bool
     */
    public static function add_card($bank_code,$phone,$province,$city,$bank_card,$user_id)
    {
        $array = [
            'user_id'   => $user_id,
            'bank_code' => $bank_code,
            'phone'     =>$phone,
            'province'  =>$province,
            'city'      =>$city,
            'bank_card' =>$bank_card
        ];
        //绑卡 获取 绑卡参数 用于二次绑卡推进
        $result =  Api::doRequest(Api::BIND_CARD,Api::GET,$array);
        if($result['code']!==0)
        {
            $return['code'] = 1;
            $return['msg'] =  $result['msg'];
            throw new \Exception( $return['msg']);
        }
        return $result['data']['ticket'];
    }

    /**
     * 绑定银行卡推进
     * @param $ticket
     * @param $valid_code
     * @return bool|mixed
     */
    public static function bind_card_advance($ticket,$valid_code){
        $bank['ticket'] = $ticket;
        $bank['valid_code'] = $valid_code;
        $result =  Api::doRequest(Api::BIND_CARD_ADVANCE,Api::GET,$bank);
        return $result;
    }


    /**
     *  设置支付密码
     * @param user_id  int  用户uid
     * @return bool|mixed
     */
    public static function set_pay_password_status($user_id)
    {

        User::where('uid',$user_id)->update(['is_set_pay_password' => 1]);
        return true;
    }
    
    /**
     * 商户充值
     * @param type $param
     * @return type
     */
    public static function accountRecharge($param)
    {
        return Api::doRequest(Api::RECHARGE_MONEY,Api::GET,$param);
    }
    
    /**
     * 商户提现
     * @param type $param
     * @return type
     */
    public static function accountWithdraw($param)
    {
        return Api::doRequest(Api::WITHDRAW_MONEY,Api::GET,$param);
    }


    /**
     * @param $company array   公司信息
     * @param $user_id  int  用户标识
     * @param $email  int  企业邮箱
     * @param $image  array  图片文件
     * @return bool|mixed
     * @throws \think\Exception
     */
    public static function setCompanyInfo($company,$user_id,$email,$image)
    {
        //上传资质材料
        $upload = static::Material_uploading($user_id,$image);

        if($upload['code']!==0)
        {
            //上传失败
            throw new \think\Exception('上传失败');
        }
        try{

            //$company['platform'] = 5;
            //$company['referrer']  = '';
            $company['file_name']= $upload['filename'];         //文件位置
            $company['user_id']= $user_id;
            $company['card_attribute']='B';           //卡属性  只支持B 对公
            $company['card_type']='DEBIT';//卡类型  只支持借记卡
            $company['digest'] = $upload['md5'];
            $company['digestType']='MD5';      //新浪验证加密方法
            $company['cert_type']='IC';        //当前法人证件只认身份证
            $company['create_time']=time();
            $company['cert_type']='IC';
            $company['email']= $email;

            $mod_company = UserCompany::where('user_id',$user_id)->find();

            if(!$mod_company){
                UserCompany::create($company);
            }
            else{
                if($mod_company['status'] > 0){
                    throw new \think\Exception('该企业已通过资质认证');
                }
                UserCompany::where('user_id',$user_id)->update($company);
            }


            $array['uid']=$user_id;
            $Reply= Api::doRequest(Api::VALIDATE_COMPANY_APTITUDE,Api::GET,$array);
            if($Reply['code']!==0)
            {
                $Reply['code']=1;
                throw new \think\Exception($Reply['msg']);
            }
            $update['name'] = $company['company_name'];
            $update['updated_at'] =time();
            db('merchant')->where('user_id='.$user_id)->update($update);
            User::where('uid',$user_id)->update(['real_name' => $company['company_name']]);
        }catch (\Exception $e){

            throw new \think\Exception($e->getMessage());
        }

        return true;
    }

    //资质文件操作 方法
    public static function Material_uploading($user_id,$images)
    {
        //根据用户生成uid 来创建属于商户自己的文件夹

        //企业文件的目录
        $Path = config('company_file_path');
        $dir = ROOT_PATH . $Path . $user_id;

        if (!file_exists($dir)) {
            mkdir($dir);
        }



        $zip_name = $user_id . '.zip';

        $zip_path = $dir . '/' . $zip_name;

        //如果已存在压缩文件则删除
        if (file_exists($zip_path)) {
            unlink($zip_path);
        }

        //创建商户自己的图片文件夹 根据商户的User_id;
        $component = new Component();
        $component->create_dir($dir);


        $UpYun = config('upyun_config.upaiyun');


        //将商户的 图片信息 重新命名移动到该商户下的文件夹  用做开户需要
        foreach ($images as $key => $value) {

            if (!copy($UpYun .'/' .$value, iconv("UTF-8", "GBK", $dir . '/' . $key . '.jpg'))) {
                throw new \think\Exception('图片处理有误，请稍后重试');
            }

        }
        //将文件企业审核资质材料生成压缩文件
        $rs = $component->create_zip($zip_path, $dir,  $user_id.'/');
        if (!$rs) {
            throw new Exception('压缩包压缩出错');
        }

        if (filesize($zip_path) > 1048576 * 5) {
            //如果图片文件过大删除当前文件夹
            unlink($zip_path);
            throw new \think\Exception('图片文件过大请重新更换图片' );

        }

        //throw new \think\Exception('ok' );

        //将资质文件上传到指定文件夹;
        $Ftps = new Sftp();
        if (!$Ftps->sftp_upload($zip_path,$zip_name)) {
            $Reply['code'] = 1;
            $Reply['msg'] = '资质上传失败，请稍后重试';
        }


        $Reply['code'] = 0;
        $Reply['md5'] = md5_file($zip_path);
        $Reply['filename'] = $zip_name;
        return $Reply;
    }



}